<template>
	<div
		style="
			border: 1px solid #ccc;
			overflow-x: hidden;
			position: relative;
			overflow-y: hidden;
		"
	>
		<div>
			<div
				style="
					display: flex;
					flex-direction: column;
					justify-content: center;
				"
			>
				<div>
					<el-select
						v-model="category"
						placeholder="博客分类"
						style="width: 100%"
					>
						<el-option
							v-for="(item, index) in categoryList"
							:key="index"
							:label="item.categoryname"
							:value="item.categoryname"
						/>
					</el-select>
				</div>
				<div>
					<imgUpload
						:marginTop="'0vh'"
						:isShow="false"
						CropWidth="1920px"
						CropHeight="1080px"
						:fixed="false"
						btnMarginTop="0vh"
						btnText="确定分类和博客封面"
						uploadWidth="100%"
					></imgUpload>
				</div>
			</div>
			<div>
				<el-input
					v-model="title"
					style="
						width: 100%;
						height: 10vh;
						border-top: none;
						border-left: none;
						border-right: none;
						font-size: 5vh;
						font-weight: bold;
					"
					size="large"
					placeholder="请输入标题（30字以内）"
					maxlength="30"
					show-word-limit
					type="text"
				/>
			</div>
			<Toolbar
				style="border-bottom: 1px solid #ccc"
				:editor="editorRef"
				:defaultConfig="toolbarConfig"
				:mode="mode"
			/>

			<Editor
				style="overflow-y: hidden; width: 70vw; min-height: 400px"
				v-model="valueHtml"
				:defaultConfig="editorConfig"
				:mode="mode"
				@onCreated="handleCreated"
			/>
		</div>
		<div>
			<el-button
				type="primary"
				size="large"
				style="width: 100%; border-radius: 0%"
				@click="submitBlog"
				>提交至服务器</el-button
			>
		</div>
	</div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {
	onBeforeUnmount,
	ref,
	shallowRef,
	onMounted,
	onBeforeMount,
} from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import axios from 'axios';
import imgUpload from './imgUpload.vue';
import { useRouter } from 'vue-router';

export default {
	components: { Editor, Toolbar },
	setup() {
		const router = useRouter();
		const category = ref('');
		const categoryList = ref([]);
		const title = ref('');
		// 编辑器实例，必须用 shallowRef
		const editorRef = shallowRef();
		// 内容 HTML
		const valueHtml = ref('');

		const toolbarConfig = { excludeKeys: ['insertVideo', 'fullScreen'] };
		const editorConfig = { placeholder: '正文区域', MENU_CONF: {} };
		editorConfig.MENU_CONF['uploadImage'] = {
			server: 'http://localhost:5000/uploadBlogImage',
			// form-data fieldName ，默认值 'wangeditor-uploaded-image'
			fieldName: 'blogImageFile',
			meta: {
				username: localStorage.getItem('username'),
				dateNow: Date.now(),
			},
			// 最多可上传几个文件，默认为 100
			maxNumberOfFiles: 10,
			// 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
			allowedFileTypes: ['image/*'],
			// 将 meta 拼接到 url 参数中，默认 false
			metaWithUrl: false,
			onSuccess(file, res) {
				console.log(res.data);
			},
		};
		editorConfig.MENU_CONF['uploadVideo'] = {
			// form-data fieldName ，默认值 'wangeditor-uploaded-video'
			fieldName: 'blogVideoFile',
			// 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
			allowedFileTypes: ['video/*'],
			// 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
			meta: {
				username: localStorage.getItem('username'),
			},
		};
		// 组件销毁时，也及时销毁编辑器
		onBeforeUnmount(() => {
			const editor = editorRef.value;
			if (editor == null) return;
			editor.destroy();
		});
		onBeforeMount(async () => {
			try {
				const res = await axios({
					baseURL: 'http://localhost:5000',
					url: '/getCategory',
					method: 'get',
				});
				if (res.data.state === 'ok') {
					console.log(res.data.data);
					categoryList.value = res.data.data;
				} else {
					return ElNotification({
						title: 'Error',
						message: '获取博客分类失败，请联系管理员',
						type: 'error',
					});
				}
			} catch (error) {
				console.log(error);
				return ElNotification({
					title: 'Error',
					message: '获取博客分类失败，请联系管理员',
					type: 'error',
				});
			}
		});

		const handleCreated = (editor) => {
			editorRef.value = editor; // 记录 editor 实例，重要！
		};
		const submitBlog = async () => {
			if (title.value) {
				if (valueHtml.value.length < 20) {
					return ElNotification({
						title: 'Warning',
						message: '请再写点吧',
						type: 'warning',
					});
				} else {
					if (category.value) {
						try {
							if (sessionStorage.getItem('imgUrl')) {
								console.log(sessionStorage.getItem('imgUrl'));
								const res = await axios({
									baseURL: 'http://localhost:5000',
									url: '/uploadBlog',
									method: 'post',
									data: {
										title: title.value,
										category: category.value,
										content: valueHtml.value,
										username:
											localStorage.getItem('username'),
										cover: sessionStorage.getItem('imgUrl'),
										uploadDate: new Date(),
									},
								});
								if (res.data.state === 'ok') {
									ElNotification({
										title: 'Success',
										message: '上传成功',
										type: 'success',
									});
									setTimeout(() => {
										router.push('/');
									}, 2000);
								} else {
									return ElNotification({
										title: 'Error',
										message: '上传失败',
										type: 'error',
									});
								}
							} else {
								const res = await axios({
									baseURL: 'http://localhost:5000',
									url: '/uploadBlog',
									method: 'post',
									data: {
										title: title.value,
										category: category.value,
										content: valueHtml.value,
										username:
											localStorage.getItem('username'),
										uploadDate: new Date(),
									},
								});
								if (res.data.state === 'ok') {
									ElNotification({
										title: 'Success',
										message: '上传成功',
										type: 'success',
									});
									setTimeout(() => {
										router.push('/');
									}, 2000);
								} else {
									return ElNotification({
										title: 'Error',
										message: '上传失败',
										type: 'error',
									});
								}
							}
						} catch (error) {
							console.log(error);
							return ElNotification({
								title: 'Error',
								message: '服务器错误',
								type: 'error',
							});
						}
					} else {
						return ElNotification({
							title: 'Warning',
							message: '请选择分类哦',
							type: 'warning',
						});
					}
				}
			} else {
				return ElNotification({
					title: 'Warning',
					message: '您还未输入标题',
					type: 'warning',
				});
			}
		};

		return {
			editorRef,
			valueHtml,
			mode: 'simple', // 或 'simple'
			toolbarConfig,
			editorConfig,
			handleCreated,
			title,
			submitBlog,
			categoryList,
			category,
			router,
		};
	},
};
</script>
<style scoped>
:deep(div.w-e-scroll) {
	height: 400px;
}
:deep(.el-upload) {
	width: 70vw;
}
</style>
